using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using Kg2TonBAL;
using LanguageConstants;
using log4net;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
using ExportToExcel;

public partial class AgroFPM1_UploadMasters : System.Web.UI.Page
{
    GrowerDetailsBAL objGrowerDetailsBAL = new GrowerDetailsBAL();
    static string ExcelSheetName = string.Empty;
    static string UploadedFilename = string.Empty;
    static string FileExtension = string.Empty;
    public DataTable dtSheetname;
    static bool isSuccess = false;
    static int ColumnCount;
    LanguageConstants.GlobalLanguageConstants LangConstants;
    private static readonly ILog log = LogManager.GetLogger(typeof(AgroFPM1_UploadMasters));
    SqlConnection Connection = new SqlConnection(EncriptManager.Decrypt(ConfigurationManager.AppSettings["fpm_connection"]));
    DataTable dtExceldata = new DataTable();
    HashSet<String> objErrorResponses = new HashSet<string>();
    Dictionary<String, String> lstErrors = new Dictionary<String, String>();
    DataSet dsparentfunctions = new DataSet();
    fpm_dataaccess da = new fpm_dataaccess();
    DataSet dsfunctions = new DataSet();
    static int function_count;
    int parentcount;
    static MenuItem[] childmenus;
    FIDetailsBAL objFIDetailsBAL = new FIDetailsBAL();
    protected void Page_Load(object sender, EventArgs e)
    {
        // Adds Try Catch Block along with Log file.
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        try
        {
            if (Session[GlobalConstants.Language] != null)
                LangConstants = new GlobalLanguageConstants(Session[GlobalConstants.Language].ToString());
            else
                Response.Redirect(GlobalLanguageConstants.IndexURL);

            if (IsPostBack)
            {
                if (Session["dtExceldataHeaders"] != null)
                    ASPxGridViewViewUploadedData.DataSource = (DataTable)Session["dtExceldataHeaders"];
                ASPxGridViewViewUploadedData.DataBind();
            }
            if (!IsPostBack)
            {
                getload();
            }

        }
        catch (Exception ex)
        {
            log.Error("Error: " + ex);
        }
        finally
        {
        }
        log.Debug("End: " + methodBase.Name);


    }

    protected void ASPxButtonDownload_Click(object sender, EventArgs e)
    {
        if (Session["exportDataErrors"] != null)
        {
            DataTable dt = new DataTable();
            dt = Session["exportDataErrors"] as DataTable;
            DataSet objdatasetExport = new DataSet();
            objdatasetExport.Tables.Add(dt.Copy());
            ExcelExporter obj = new ExcelExporter(this);
            obj.ExportDataSet(objdatasetExport, GlobalConstants.exportExcelErrorReport);
        }
        else
        {
            ASPxPopupControl.ShowOnPageLoad = true;
            ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.None;
            ASPxPopupControl.Height = 50;
            ASPxPopupControl.Width = 330;
            lblMessage.Text = "There is no file to download";
        }
    }

    protected void ASPxButtonUpload_Click(object sender, EventArgs e)
    {
        // Adds Try Catch Block along with Log file.
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        try
        {
            if (ASPxUploadControl.HasFile)
            {
                UploadedFilename = ASPxUploadControl.FileName;
                FileExtension = Path.GetExtension(ASPxUploadControl.FileName.ToLower());
                if ((FileExtension == ".xls") || (FileExtension == ".xlsx"))
                {

                    GetDataFromExcelSheet();
                }
                else
                {
                    ASPxPopupControl.ShowOnPageLoad = true;
                    ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.None;
                    ASPxPopupControl.Height = 50;
                    ASPxPopupControl.Width = 330;
                    lblMessage.Text = LangConstants.errmsgSelectAFileWithxlsorxlsxExtensionToUpload;
                }

            }
            else
            {
                // ScriptAlert = "<script>alert('" + objGlobalConstants.errmsgSelectAFileToUpload + "')</script>";
                //ScriptManager.RegisterStartupScript(this.Page, typeof(string), "Select A File", ScriptAlert, false);
                ASPxPopupControl.ShowOnPageLoad = true;
                ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.None;
                ASPxPopupControl.Height = 50;
                ASPxPopupControl.Width = 230;
                lblMessage.Text = LangConstants.errmsgSelectAFileToUpload;
                //lblErrorMessage.Visible = true;
                //lblErrorMessage.Text = objGlobalConstants.errmsgSelectAFileToUpload;
            }

        }
        catch (Exception ex)
        {
            log.Error("Error: " + ex);
        }
        finally
        {
        }
        log.Debug("End: " + methodBase.Name);

    }

    /// <summary>
    /// Retrives Data From Excel Sheet, Dumps In Table And Shows On Grid
    /// </summary>
    private void GetDataFromExcelSheet()
    {
        // Adds Try Catch Block along with Log file.
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        string AliasToUploadedFile = string.Empty;
        try
        {
            string strConExcel = string.Empty;
            Random Rand = new Random();
            if (System.IO.Path.GetExtension(FileExtension) == ".xlsx")
            {
                log.Debug("Begin:SaveFile as.xlsx");
                //string[] Files = Directory.GetFiles(Server.MapPath("GrowsersUploadFiles"));
                //if (Files != null && Files.Count() > 0)
                //{
                //    foreach (string file in Files)
                //    {
                //        File.Delete(file);
                //    }
                //}
                AliasToUploadedFile = Server.MapPath("GrowsersUploadFiles\\" + Session["U_ID"] + "" + Rand.Next() + ".xlsx");

                log.Debug("Begin:AliasToUploadedFile" + AliasToUploadedFile);
                ASPxUploadControl.SaveAs(AliasToUploadedFile);
                log.Debug("Begin:Save Successfully");
                // "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AliasToUploadedFile + ";Excel 12.0;HDR=Yes;IMEX=2";
                //  strConExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + AliasToUploadedFile + ";Extended Properties=\"Excel 8.0;IMEX=1\";";
                strConExcel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AliasToUploadedFile + ";Excel 12.0;HDR=Yes;IMEX=2";
            }
            else if (System.IO.Path.GetExtension(FileExtension) == ".xls")
            {
                log.Debug("Begin:SaveFile as .xls");
                //string[] Files = Directory.GetFiles(Server.MapPath("GrowsersUploadFiles"));
                //if (Files != null && Files.Count() > 0)
                //{
                //    foreach (string file in Files)
                //    {
                //        File.Delete(file);
                //    }
                //}
                AliasToUploadedFile = Server.MapPath("GrowsersUploadFiles\\" + Session["U_ID"] + "" + Rand.Next() + ".xls");
                log.Debug("Begin:AliasToUploadedFile" + AliasToUploadedFile);
                ASPxUploadControl.SaveAs(AliasToUploadedFile);
                // strConExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + AliasToUploadedFile + ";Extended Properties=\"Excel 8.0;IMEX=1\";";
                strConExcel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AliasToUploadedFile + ";Excel 12.0;HDR=Yes;IMEX=2";
            }
            else if (System.IO.Path.GetExtension(FileExtension) == ".xml")
            {
                log.Debug("Begin:SaveFile as .xml");
                AliasToUploadedFile = Server.MapPath(Session["U_ID"] + "" + Rand.Next() + ".xml");
                log.Debug("Begin:AliasToUploadedFile" + AliasToUploadedFile);
                ASPxUploadControl.SaveAs(AliasToUploadedFile);
                log.Debug("Begin:Save Successfully");
                // strConExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + AliasToUploadedFile + ";Extended Properties=\"Excel 8.0;IMEX=1\";";
                strConExcel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AliasToUploadedFile + ";Excel 12.0;HDR=Yes;IMEX=2";
            }

            log.Debug("Begin:Before Using");
            using (OleDbConnection oledbconnectExcel = new OleDbConnection(strConExcel))
            {
                log.Debug("Begin:In Using");
                oledbconnectExcel.Open();
                dtSheetname = oledbconnectExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                log.Debug("Begin:Result Set");
                var dtResult = dtSheetname.Select("Table_Name like 'Sheet1$%'");
                log.Debug("Begin:Result Set length" + dtResult.Length);
                if (dtResult.Length == 1)
                {
                    log.Debug("Begin:dtSheet Name");
                    dtSheetname = dtResult.CopyToDataTable();
                    ExcelSheetName = dtSheetname.Rows[0]["Table_Name"].ToString();
                    string STR_SelectFromFormat = "SELECT * FROM  [Sheet1$]";
                    OleDbCommand cmdselect = new OleDbCommand(STR_SelectFromFormat, oledbconnectExcel);
                    OleDbDataAdapter DataadaptExcel = new OleDbDataAdapter(cmdselect);
                    cmdselect.ExecuteNonQuery();
                    DataadaptExcel.Fill(dtExceldata);
                    DataTable dtExceldataHeaders = dtExceldata.Copy();



                    for (int i = 0; i < dtExceldata.Rows.Count; i++)
                    {
                        for (int j = 0; j < dtExceldata.Columns.Count; j++)
                        {
                            if (dtExceldata.Rows[i][j].ToString() == "NA" || dtExceldata.Rows[i][j].ToString().Trim() == "" || dtExceldata.Rows[i][j].ToString().Trim() == string.Empty || dtExceldata.Rows[i][j] == null)
                            {
                                dtExceldata.Rows[i][j] = 0;
                                dtExceldata.AcceptChanges();
                            }
                        }
                        dtExceldata.AcceptChanges();
                    }
                    log.Debug("Begin:Delete DataTable");
                    ColumnCount = objGrowerDetailsBAL.DeleteFromTableBasedOnUserId(Convert.ToInt32(Session["U_ID"]));
                    log.Debug("Begin:Excel Column Count" + ColumnCount);
                    int UploadedExcelColumnCount = dtExceldata.Columns.Count;
                    log.Debug("Begin: Column Count" + UploadedExcelColumnCount);
                    if (ASPxGridViewViewUploadedData.Bound)
                    {
                        ASPxGridViewViewUploadedData.Columns.Clear();
                    }
                    ASPxGridViewViewUploadedData.Visible = true;
                    ASPxGridViewViewUploadedData.AutoGenerateColumns = true;
                    Session["dtExceldata"] = dtExceldata;
                    Session["dtExceldataHeaders"] = dtExceldataHeaders;
                    ASPxGridViewViewUploadedData.DataSource = dtExceldataHeaders;
                    ASPxGridViewViewUploadedData.DataBind();
                    isSuccess = true;
                    dtExceldata.Columns.Add(new DataColumn("ErrorMessage"));
                    dtExceldata.AcceptChanges();
                }
                else
                {
                    log.Debug("Begin:dtSheet Name Wrong");
                    ASPxPopupControl.ShowOnPageLoad = true;
                    ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.None;
                    ASPxPopupControl.Height = 50;
                    ASPxPopupControl.Width = 480;
                    lblMessage.Text = LangConstants.errmsgFileuploadedcontainsInvalidSheetname;
                }
                oledbconnectExcel.Close();
            }
        }

        catch (Exception ex)
        {
            log.Debug("Begin:Catch Error");
            ASPxPopupControl.ShowOnPageLoad = true;
            ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.None;
            ASPxPopupControl.Height = 50;
            ASPxPopupControl.Width = 570;
            lblMessage.Text = "Error Occured";
            isSuccess = false;
            ASPxGridViewViewUploadedData.Visible = false;
            log.Error(ex.Message);
        }

        finally
        {
        }
        log.Debug("End: " + methodBase.Name);
    }

    protected void btnPopUpOK_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/AgroFPM1/Search/GrowersUpload.aspx", false);
    }

    protected void ASPxButtonValidate_Click(object sender, EventArgs e)
    {

        if (ASPxGridViewViewUploadedData.Columns.Count <= 0)
        {
            ASPxButtonDownload.Enabled = true;
            ASPxButtonDownload.Visible = true;
            ASPxPopupControl.ShowOnPageLoad = true;
            ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.Vertical;
            ASPxPopupControl.Width = 350;
            ASPxPopupControl.Height = 200;
            lblMessage.Text = LangConstants.PleaseclickonPreviewfirst;
            return;
        }


        string strError = "";
        string strDataError = string.Empty;
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        try
        {
            dtExceldata = (DataTable)Session["dtExceldata"];
            DataTable dtExportErrors = ValidateDataType(dtExceldata);
            // checkforRegions(dtExceldataCopy);

            foreach (DataRow row in dtExportErrors.Rows)
            {
                if (row["ErrorMessage"] != null && row["ErrorMessage"].ToString() != "")
                {
                    ASPxButtonDownload.Visible = true;
                    ASPxPopupControl.ShowOnPageLoad = true;
                    ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.Vertical;
                    ASPxPopupControl.Width = 550;
                    ASPxPopupControl.Height = 300;
                    lblMessage.Text = "Error Occured please click on download to view the errors";
                    Session["exportDataErrors"] = dtExportErrors;
                    lblMessage.Visible = true;
                    return;
                }
            }


            if (!String.IsNullOrEmpty(strError))
            {

                ASPxPopupControl.ShowOnPageLoad = true;
                ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.Vertical;
                ASPxPopupControl.Width = 550;
                ASPxPopupControl.Height = 300;
                lblMessage.Text = strError;
                return;
            }
            else
            {
                Session["exportDataErrors"] = null;
                string[] FileName = UploadedFilename.Split('.');
                UploadedFilename = FileName.GetValue(0).ToString() + "{" + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "}." + FileName.GetValue(1);
                DataTable dtExceldataCopy = dtExceldata.Copy();
                if (lstErrors.Count > 0)
                {
                    dtExceldataCopy.Columns.Add("Error Message/Remarks");
                    dtExceldataCopy.Columns.Add("Sheet Name");

                    DataTable dtErrorRecords = dtExceldataCopy.Clone();

                    for (int i = 0; i < dtExceldataCopy.Rows.Count; i++)
                    {
                        String RespId = dtExceldataCopy.Rows[i]["Grower Name"].ToString();
                        if (objErrorResponses.Contains(RespId))
                        {
                            dtExceldataCopy.Rows[i]["Error Message/Remarks"] = lstErrors[RespId];
                            dtExceldataCopy.Rows[i]["Sheet Name"] = UploadedFilename;
                            DataRow dr = dtExceldataCopy.Rows[i];

                            dtErrorRecords.ImportRow(dr);
                            dtExceldataCopy.Rows.Remove(dr);
                            i--;
                        }
                    }

                    dtExceldataCopy.Columns.Remove("Error Message/Remarks");
                    dtExceldataCopy.Columns.Remove("Sheet Name");
                }

                if (dtExceldataCopy != null && ASPxGridViewViewUploadedData.Visible == true && isSuccess == true)
                {
                    int[] res = InsertExcelDataTosql(dtExceldataCopy);
                    foreach (object item in res)
                    {
                        if (Convert.ToInt32(item) == 0)
                        {
                            ASPxPopupControl.ShowOnPageLoad = true;
                            ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.Vertical;
                            ASPxPopupControl.Width = 250;
                            ASPxPopupControl.Height = 200;
                            lblMessage.Text = LangConstants.InsertionFailedpleasecheckagain;
                            break;
                        }
                        else
                        {
                            ASPxPopupControl.ShowOnPageLoad = true;
                            ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.Vertical;
                            ASPxPopupControl.Width = 250;
                            ASPxPopupControl.Height = 200;
                            lblMessage.Text = LangConstants.Valuesinsertedsuccessfully;
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ASPxPopupControl.ShowOnPageLoad = true;
            ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.Vertical;
            ASPxPopupControl.Width = 250;
            ASPxPopupControl.Height = 200;

            lblMessage.Text = strError;
            log.Error("Error: " + ex);
        }
        finally
        {

        }
        log.Debug("End: " + methodBase.Name);

    }

    private void checkforRegions(DataTable dt)
    {
        // Adds Try Catch Block along with Log file.
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        try
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string errorMessage = objGrowerDetailsBAL.CheckForRegions(dt.Rows[i]["Country"].ToString(), dt.Rows[i]["Province"].ToString(), dt.Rows[i]["District"].ToString(), dt.Rows[i]["Sub District"].ToString(), dt.Rows[i]["Crop"].ToString(), dt.Rows[i]["Product code"].ToString(), dt.Rows[i]["PDA ID"].ToString());

                if (errorMessage != "Success")
                {
                    Session["errorMessage"] = errorMessage;
                    return;
                }
            }
        }

        catch (Exception ex)
        {
            log.Error("Error: " + ex);
        }
        finally
        {
        }
        log.Debug("End: " + methodBase.Name);

    }

    private string ValidateData(DataTable dtExceldata)
    {
        // Adds Try Catch Block along with Log file.
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);

        StringBuilder sblErrorMessages = new StringBuilder();
        try
        {
            for (int row = 0; row < dtExceldata.Rows.Count; row++)
            {
                for (int nextRow = 1; nextRow < dtExceldata.Rows.Count; nextRow++)
                {
                    if ((dtExceldata.Rows[row]["Latitude"].ToString() == "0" && dtExceldata.Rows[row]["Longitude"].ToString() != "0") || (dtExceldata.Rows[row]["Latitude"].ToString() != "0" && dtExceldata.Rows[row]["Longitude"].ToString() == "0"))
                    {
                        dtExceldata.Rows[row]["ErrorMessage"] = LangConstants.Pleaseenterbothlatitudeandlongitude;
                    }
                    if ((dtExceldata.Rows[row]["Mobile"].ToString() == dtExceldata.Rows[nextRow]["Mobile"].ToString()) && (dtExceldata.Rows[row]["Grower ID"].ToString() != dtExceldata.Rows[nextRow]["Grower ID"].ToString()))
                    {
                        dtExceldata.Rows[row]["ErrorMessage"] = LangConstants.Notwogrowersshouldhavesamemobilenumber + dtExceldata.Rows[row]["Grower Name"].ToString() + ',' + dtExceldata.Rows[nextRow]["Grower Name"].ToString() + ")";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            log.Error("Error: " + ex);
        }
        finally
        {
        }
        log.Debug("End: " + methodBase.Name);

        return sblErrorMessages.ToString();
    }

    public void BulkInsertsErrors(DataTable dt)
    {
        // Adds Try Catch Block along with Log file.
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        try
        {
            DataTable table = dt;
            log.Debug("Connection :" + Connection.State);
            if (Connection.State == ConnectionState.Closed)
            {
                Connection.Open();
            }
            log.Debug("Connection :" + Connection.State);
            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(Connection))
            {
                bulkCopy.DestinationTableName = "tbl_validatedataErrors";
                dt.Columns.Add(new DataColumn("Created By", typeof(int)));
                dt.Columns.Add(new DataColumn("Created Date", typeof(DateTime)));
                dt.Columns.Add(new DataColumn("Updated By", typeof(int)));
                dt.Columns.Add(new DataColumn("Updated Date", typeof(DateTime)));

                foreach (DataRow Row in dt.Rows)
                {
                    Row["Created By"] = Session["U_ID"];
                    Row["Created Date"] = DateTime.Now;
                    Row["Updated By"] = Session["U_ID"];
                    Row["Updated Date"] = DateTime.Now;
                }
                foreach (DataColumn item in dt.Columns)
                {
                    bulkCopy.ColumnMappings.Add(item.ColumnName, item.ColumnName);
                }
                log.Debug("Bulk Copy Start");
                bulkCopy.WriteToServer(dt);
                log.Debug("Bulk Copy End");
            }

        }
        catch (Exception ex)
        {
            log.Error("Error: " + ex);
        }
        finally
        {
        }
        log.Debug("End: " + methodBase.Name);
    }
    protected void ASPxButtonStatesUpload_Click(object sender, EventArgs e)
    {

        //if (ASPxGridViewViewUploadedData.Columns.Count <= 0)
        //{
        //    ASPxButtonDownload.Enabled = true;
        //    ASPxButtonDownload.Visible = true;
        //    ASPxPopupControl.ShowOnPageLoad = true;
        //    ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.Vertical;
        //    ASPxPopupControl.Width = 350;
        //    ASPxPopupControl.Height = 200;
        //    lblMessage.Text = LangConstants.PleaseclickonPreviewfirst;
        //    return;
        //}


        string strError = "";
        string strDataError = string.Empty;
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        try
        {
           
            DataTable dtExportErrors = ValidateDataType(dtExceldata);
            // checkforRegions(dtExceldataCopy);

         


         
                Session["exportDataErrors"] = null;
               // string[] FileName = UploadedFilename.Split('.');
                UploadedFilename = "States" + "{" + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + "}";//." + FileName.GetValue(1);
                
               
                GetDataFromExcelSheet();
                dtExceldata = (DataTable)Session["dtExceldata"];
                DataTable dtExceldataCopy = dtExceldata.Copy();
                if (dtExceldataCopy != null )
                {
                    int[] res = InsertStatesExcelDataTosql(dtExceldataCopy);
                    foreach (object item in res)
                    {
                        if (Convert.ToInt32(item) == 0)
                        {
                            ASPxPopupControl.ShowOnPageLoad = true;
                            ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.Vertical;
                            ASPxPopupControl.Width = 250;
                            ASPxPopupControl.Height = 200;
                            lblMessage.Text = LangConstants.InsertionFailedpleasecheckagain;
                            break;
                        }
                        else
                        {
                            ASPxPopupControl.ShowOnPageLoad = true;
                            ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.Vertical;
                            ASPxPopupControl.Width = 250;
                            ASPxPopupControl.Height = 200;
                            lblMessage.Text = LangConstants.Valuesinsertedsuccessfully;
                        }
                    }
                }
            
        }
        catch (Exception ex)
        {
            ASPxPopupControl.ShowOnPageLoad = true;
            ASPxPopupControl.ScrollBars = System.Web.UI.WebControls.ScrollBars.Vertical;
            ASPxPopupControl.Width = 250;
            ASPxPopupControl.Height = 200;

            lblMessage.Text = strError;
            log.Error("Error: " + ex);
        }
        finally
        {

        }
        log.Debug("End: " + methodBase.Name);

    }
    public int[] InsertStatesExcelDataTosql(DataTable dt)
    {
        // Adds Try Catch Block along with Log file.
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        int[] res = new int[dt.Rows.Count];
        try
        {

            for (int i = 0; i < dt.Rows.Count; i++)
            {

                res[i] = objGrowerDetailsBAL.importStatesDetails(dt.Rows[i]["state_id"].ToString(), dt.Rows[i]["state_name"].ToString(), dt.Rows[i]["state_shortcode"].ToString());
            }

        }
        catch (Exception ex)
        {
            log.Error("Error: " + ex);
        }
        finally
        {
        }
        log.Debug("End: " + methodBase.Name);
        return res;
    }
    public int[] InsertExcelDataTosql(DataTable dt)
    {
        // Adds Try Catch Block along with Log file.
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        int[] res = new int[dt.Rows.Count];
        try
        {

            for (int i = 0; i < dt.Rows.Count; i++)
            {

                res[i] = objGrowerDetailsBAL.importGrowerDetails(dt.Rows[i]["Grower ID"].ToString(), dt.Rows[i]["Contract Number"].ToString(), dt.Rows[i]["Grower Name"].ToString(), null,
                dt.Rows[i]["PDA ID"].ToString(), null, dt.Rows[i]["Surname"].ToString(), dt.Rows[i]["Mobile"].ToString(),
                dt.Rows[i]["Country"].ToString(), dt.Rows[i]["Province"].ToString(), dt.Rows[i]["District"].ToString(), dt.Rows[i]["Sub District"].ToString(),
                null, dt.Rows[i]["Contracted Rai"].ToString(), dt.Rows[i]["Crop"].ToString(), dt.Rows[i]["Product code"].ToString(),
                dt.Rows[i]["Season name"].ToString(), dt.Rows[i]["Year"].ToString(), dt.Rows[i]["Organizer Name"].ToString(),
                1.ToString(), null, dt.Rows[i]["Latitude"].ToString(), dt.Rows[i]["Longitude"].ToString(), dt.Rows[i]["Organizer Mobile Number"].ToString(), Convert.ToInt32(dt.Rows[i]["Contracted Rai"]));
            }

        }
        catch (Exception ex)
        {
            log.Error("Error: " + ex);
        }
        finally
        {
        }
        log.Debug("End: " + methodBase.Name);
        return res;
    }

    public DataTable ValidateDataType(DataTable dtfromExcel)
    {
        // Adds Try Catch Block along with Log file.
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        try
        {
            SqlCommand cmd = new SqlCommand("spGetExcelStructureForGrowerReg", Connection);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

            DataTable dtActual = ds.Tables[0];
            StringBuilder sblErrorMessages = new StringBuilder();

            if (dtfromExcel != null)
            {
                if (dtActual.Columns.Count == dtfromExcel.Columns.Count - 1)
                {
                    for (int j = 0; j < dtActual.Columns.Count; j++)
                    {

                        if (dtActual.Columns[j].ColumnName != dtfromExcel.Columns[j].ColumnName)
                        {
                            sblErrorMessages.Append("[Columns Missmatch] " + "Actual Column-" +
                                                    dtActual.Columns[j].ColumnName + ", Excel Column-" +
                                                    dtfromExcel.Columns[j].ColumnName);
                        }
                    }
                    if (String.IsNullOrEmpty(sblErrorMessages.ToString()))
                    {
                        for (int i = 0; i < dtfromExcel.Rows.Count; i++)
                        {
                            string grower_name = Convert.ToString(dtfromExcel.Rows[i]["Grower Name"]);
                            for (int j = 0; j < dtActual.Columns.Count; j++)
                            {

                                DataColumn dcColumn = dtActual.Columns[j];
                                String Column = dcColumn.ColumnName;
                                String columnData = Convert.ToString(dtfromExcel.Rows[i][j]).Trim();

                                bool IsNotEmpty = !String.IsNullOrEmpty(columnData);
                                if (dcColumn.DataType == typeof(string))
                                {
                                    if (columnData.Length > 50)
                                    {
                                        dtfromExcel.Rows[i]["ErrorMessage"] += "," + Column + " Lenght exceeded 50";
                                    }
                                    else
                                    {
                                        var resSpecialChars = CheckSpecialChars(columnData);
                                        if (Column == "Grower ID")
                                        {
                                            if (columnData.Length == 0 || columnData == "0")
                                            {
                                                dtfromExcel.Rows[i]["ErrorMessage"] += "," + Column + " should not be empty";
                                            }
                                            foreach (char ch in columnData)
                                            {
                                                if (!Char.IsDigit(ch))
                                                {
                                                    dtfromExcel.Rows[i]["ErrorMessage"] += "," + Column + " should contain only digits";
                                                    break;
                                                }
                                            }
                                        }
                                        else if ((Column == "Village Name" || Column == "Grower Name" || Column == "Country" || Column == "Province" || Column == "District" || Column == "Sub District"))
                                        {
                                            if (columnData != null && (columnData == "0" || columnData.Length <= 0))
                                                dtfromExcel.Rows[i]["ErrorMessage"] += "," + Column + " should not be empty";
                                            else
                                            {
                                                foreach (char ch in columnData)
                                                {
                                                    if (!Char.IsLetter(ch) && !((int)ch == 32))
                                                    {
                                                        dtfromExcel.Rows[i]["ErrorMessage"] += "," + Column + " should contain only letters";
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        else if (Column == "Season name")
                                        {
                                            if (columnData.ToUpper() != "DRY" && columnData.ToUpper() != "WET")
                                            {
                                                dtfromExcel.Rows[i]["ErrorMessage"] += "," + Column + " Should be either Dry or Wet";
                                            }
                                        }
                                        else if ((Column == "Mobile" && columnData != "0") || (Column == "Organizer Mobile Number" && columnData != "0"))
                                        {
                                            foreach (char ch in columnData)
                                            {
                                                if (!Char.IsDigit(ch))
                                                {
                                                    dtfromExcel.Rows[i]["ErrorMessage"] += "," + Column + " Number should be valid";
                                                    break;
                                                }
                                            }
                                            if (columnData.Length > 12 || columnData.Length < 10)
                                                dtfromExcel.Rows[i]["ErrorMessage"] += "," + Column + " Number should be valid";
                                        }

                                        else if (resSpecialChars && IsNotEmpty)
                                        {
                                            dtfromExcel.Rows[i]["ErrorMessage"] += "," + Column + " should not contain any special characters";
                                        }
                                    }
                                }
                                else if (dcColumn.DataType == typeof(decimal))
                                {
                                    decimal value;

                                    if (!Decimal.TryParse(columnData, out value) && IsNotEmpty)
                                    {
                                        dtfromExcel.Rows[i]["ErrorMessage"] += "," + "Error at " + Column;
                                    }
                                }
                                else if (dcColumn.DataType == typeof(float))
                                {
                                    float value;
                                    if (!float.TryParse(columnData, out value) && IsNotEmpty)
                                    {
                                        dtfromExcel.Rows[i]["ErrorMessage"] += "," + "Error at " + Column;
                                    }
                                }
                                else if (dcColumn.DataType == typeof(double))
                                {
                                    double value;
                                    if (!double.TryParse(columnData, out value) && IsNotEmpty)
                                    {
                                        dtfromExcel.Rows[i]["ErrorMessage"] += "," + "Error at " + Column;
                                    }
                                }
                                else if (dcColumn.DataType == typeof(int))
                                {
                                    foreach (char ch in columnData)
                                    {
                                        if (!Char.IsDigit(ch))
                                        {
                                            dtfromExcel.Rows[i]["ErrorMessage"] += "," + "Enter only digits for" + Column;
                                            break;
                                        }
                                    }

                                    if (columnData == "0" && columnData != null)
                                    {
                                        dtfromExcel.Rows[i]["ErrorMessage"] += "," + "Error at " + Column;
                                    }
                                }
                                else if (dcColumn.DataType == typeof(Int16))
                                {
                                    Int16 value;
                                    if (!Int16.TryParse(columnData, out value) && IsNotEmpty)
                                    {
                                        dtfromExcel.Rows[i]["ErrorMessage"] += "," + "Error at " + Column;
                                    }
                                }
                                else if (dcColumn.DataType == typeof(DateTime))
                                {
                                    DateTime value;
                                    string[] format = new string[] { "dd-MM-yyyy" };
                                    bool res = DateTime.TryParseExact(columnData, format, CultureInfo.InvariantCulture,
                                                                      DateTimeStyles.NoCurrentDateDefault, out value);
                                    if (!res && IsNotEmpty)
                                    {
                                        dtfromExcel.Rows[i]["ErrorMessage"] += "," + "Error at " + Column;
                                    }
                                }
                            }
                            if (dtfromExcel.Rows[i]["ErrorMessage"].ToString().Length > 0)
                                dtfromExcel.Rows[i]["ErrorMessage"].ToString().Remove(0, 1);
                        }
                        Session["exportDataErrors"] = dtfromExcel;
                    }
                }
                else
                {
                    sblErrorMessages.Append(LangConstants.NumberofColumnsMissmatchinExcel);
                }
            }
            else
            {
                sblErrorMessages.Append(LangConstants.NumberofColumnsMissmatchinExcel);
            }

            if (objErrorResponses.Count > 20)
            {
                sblErrorMessages.Append(LangConstants.Morethan20responseshasinvaliddata + String.Join("<br />", objErrorResponses.ToArray()));
            }
            Session["errors"] = sblErrorMessages.ToString();


            for (int i = 0; i < dtfromExcel.Rows.Count; i++)
            {
                string errorMessage = objGrowerDetailsBAL.CheckForRegions(dtfromExcel.Rows[i]["Country"].ToString(), dtfromExcel.Rows[i]["Province"].ToString(), dtfromExcel.Rows[i]["District"].ToString(), dtfromExcel.Rows[i]["Sub District"].ToString(), dtfromExcel.Rows[i]["Crop"].ToString(), dtfromExcel.Rows[i]["Product code"].ToString(), dtfromExcel.Rows[i]["PDA ID"].ToString());

                if (errorMessage != "Success")
                {
                    string[] errors = errorMessage.Split(',');

                    if (errors.Length > 1)
                    {
                        dtfromExcel.Rows[i]["ErrorMessage"] += "," + "Please enter correct ";
                        for (int err = 1; err < errors.Length; err++)
                        {
                            dtfromExcel.Rows[i]["ErrorMessage"] += errors[err] + ",";
                        }

                    }
                }
            }

            for (int row = 0; row < dtfromExcel.Rows.Count; row++)
            {
                for (int nextRow = 1; nextRow < dtfromExcel.Rows.Count; nextRow++)
                {
                    if ((dtfromExcel.Rows[row]["Latitude"].ToString() == "0" && dtfromExcel.Rows[row]["Longitude"].ToString() != "0") || (dtfromExcel.Rows[row]["Latitude"].ToString() != "0" && dtfromExcel.Rows[row]["Longitude"].ToString() == "0"))
                    {
                        dtfromExcel.Rows[row]["ErrorMessage"] += "," + "Please enter both latitude and longitude";
                    }
                    if ((dtExceldata.Rows[row]["Mobile"].ToString() != "0") && (dtExceldata.Rows[row]["Mobile"].ToString() == dtfromExcel.Rows[nextRow]["Mobile"].ToString()) && (dtfromExcel.Rows[row]["Grower ID"].ToString() != dtfromExcel.Rows[nextRow]["Grower ID"].ToString()))
                    {
                        dtfromExcel.Rows[row]["ErrorMessage"] += "," + "No two growers should have same mobile number(" + dtExceldata.Rows[row]["Grower Name"].ToString() + ',' + dtExceldata.Rows[nextRow]["Grower Name"].ToString() + ")";
                    }
                }
            }

            return dtfromExcel;

        }
        catch (Exception ex)
        {
            log.Error("Error: " + ex);
        }
        finally
        {
        }
        log.Debug("End: " + methodBase.Name);
        return null;
    }

    private bool CheckSpecialChars(String str)
    {

        // Adds Try Catch Block along with Log file.
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        try
        {
            char[] SpecialChars = @"!@#$%^&*(){}|<>?;`~=+*[]".ToCharArray();//Srinu
            int indexOf = str.IndexOfAny(SpecialChars);
            if (indexOf == -1)
            {
                return false;
            }
        }
        catch (Exception ex)
        {
            log.Error("Error: " + ex);
        }
        finally
        {

        }
        log.Debug("End: " + methodBase.Name);
        return true;
    }


    private bool isChineeseString(string word)
    {

        bool isChineese = false;
        // Adds Try Catch Block along with Log file.
        System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame();
        System.Reflection.MethodBase methodBase = stackFrame.GetMethod();
        log.Debug("Start: " + methodBase.Name);
        try
        {

            for (int x = 0; x < word.Length; x++)
            {
                if (char.GetUnicodeCategory(word[x]) == UnicodeCategory.OtherLetter || word[x] == '/' || word[x] == '\\' || word[x] == '-')
                {
                    isChineese = true;
                }
                else
                {
                    isChineese = false;
                    break;
                }
            }
        }
        catch (Exception ex)
        {
            log.Error("Error: " + ex);
        }
        finally
        {

        }
        log.Debug("End: " + methodBase.Name);
        return isChineese;

    }

    List<string> lstMessages = new List<string>();
    public String ErrorString(String ResponseId, String Column, int type)
    {
        try
        {
            objErrorResponses.Add(ResponseId);
            String StrErrorforDB = ResponseId + "-" + Column + " has invalid Format" + "<br/>";
            if (lstErrors.ContainsKey(ResponseId))
            {
                lstErrors[ResponseId] += StrErrorforDB;
            }
            else
            {
                lstErrors.Add(ResponseId, StrErrorforDB);
            }
            return StrErrorforDB;
        }
        catch (Exception ex)
        {

        }
        finally
        {

        }
        return String.Empty;
    }
    protected void btnShowModel_Click(object sender, EventArgs e)
    {
        // setvisiblilityoflables(true);


    }



    protected void lbChangeLanguage_Click(object sender, EventArgs e)
    {
        ImageButton Imgbtn = (ImageButton)sender;
        string id = Imgbtn.ID;

        if (Session["Language"] != null)
        {
            if (Session["Language"] == GlobalLanguageConstants.EnglishCultureCode && id == "ImageButtonThaiFlag")
            {
                Session["Language"] = GlobalLanguageConstants.ThaiCultureCode;
                LanguageConstants.GlobalLanguageConstants obj = new GlobalLanguageConstants(GlobalLanguageConstants.ThaiCultureCode);
                Kg2TonBAL.GlobalConstants.Culture = GlobalLanguageConstants.ThaiCultureCode;
                string currentUrl = HttpContext.Current.Request.Url.LocalPath;
                Response.Redirect(currentUrl);

            }

            else if (Session["Language"] == GlobalLanguageConstants.ThaiCultureCode && id == "ImageButtonIndianFlag")
            {
                Session["Language"] = GlobalLanguageConstants.EnglishCultureCode;
                LanguageConstants.GlobalLanguageConstants obj = new GlobalLanguageConstants(GlobalLanguageConstants.EnglishCultureCode);
                Kg2TonBAL.GlobalConstants.Culture = GlobalLanguageConstants.EnglishCultureCode;
                string currentUrl = HttpContext.Current.Request.Url.LocalPath;
                Response.Redirect(currentUrl);
            }

        }

        else
        {
            Response.Redirect(GlobalLanguageConstants.IndexURL);
        }

    }

    #region BindMenu
    protected void getload()
    {
        try
        {

            if (Session[Constants_Master.dsparentfunctions] == null)
            {
                dsparentfunctions = da.fill_menu(ViewState[Constants_Master.uid].ToString());
                Session[Constants_Master.dsparentfunctions] = dsparentfunctions;
                //GETTING THE MAIN MENU ITEMS
                if (dsparentfunctions != null)
                {
                    if (dsparentfunctions.Tables.Count > 0)
                    {
                        DataView dv = new DataView();
                        dv = dsparentfunctions.Tables[0].DefaultView;
                        dv.RowFilter = Constants_Master.RowFilter;
                        DataView dv1 = dv;
                        parentcount = dv1.Count;

                        MenuItem[] parentmenu = new MenuItem[parentcount];

                        int counter = 0;

                        //ADDING 6 MENU ITEMS TO THE MAIN MENU ITEMS.

                        for (int i = 0; i < dsparentfunctions.Tables[0].Rows.Count; i++)
                        {
                            if (dsparentfunctions.Tables[0].Rows[i][2].ToString() == Constants_Master.Zero)
                            {
                                parentmenu[counter] = new MenuItem();
                                parentmenu[counter].Text = dsparentfunctions.Tables[0].Rows[i][1].ToString();
                                parentmenu[counter].NavigateUrl = dsparentfunctions.Tables[0].Rows[i][6].ToString();
                                parentmenu[counter].Value = dsparentfunctions.Tables[0].Rows[i][0].ToString();
                                Mainmenu.Items.Add(parentmenu[counter]);


                                //if (parentmenu[counter].Text == "Home")
                                //{
                                //    parentmenu[counter].NavigateUrl = "~/agrofpm1/Home.aspx";
                                //    counter = counter + 1;
                                //}

                                if (parentmenu[counter].Text != Constants_Master.LoginTimings)
                                {
                                    if (parentmenu[counter].Text != Constants_Master.Logout && parentmenu[counter].Text != "Crop Summary")
                                    {
                                        parentmenu[counter].NavigateUrl = "~/agrofpm1/Search/GoogleMapView.aspx";
                                        counter = counter + 1;
                                    }
                                    else if (parentmenu[counter].Text != "Crop Summary")
                                    {
                                        parentmenu[counter].NavigateUrl = "~/agrofpm1/Index.aspx";
                                        counter = counter + 1;
                                    }
                                }
                                else
                                {
                                    parentmenu[counter].NavigateUrl = "~/AgroFPM1/Login.aspx" + "?uname=";
                                    counter = counter + 1;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        addchilditems(dsparentfunctions, counter, parentcount, parentmenu);


                    }
                }
            }
            else
            {
                dsparentfunctions = (DataSet)Session[Constants_Master.dsparentfunctions];

                //GETTING THE MAIN MENU ITEMS
                if (dsparentfunctions != null)
                {
                    if (dsparentfunctions.Tables.Count > 0)
                    {
                        DataView dv = new DataView();
                        dv = dsparentfunctions.Tables[0].DefaultView;
                        dv.RowFilter = Constants_Master.RowFilter;
                        DataView dv1 = dv;
                        parentcount = dv1.Count;

                        MenuItem[] parentmenu = new MenuItem[parentcount];

                        int counter = 0;

                        //ADDING 6 MENU ITEMS TO THE MAIN MENU ITEMS.

                        for (int i = 0; i < dsparentfunctions.Tables[0].Rows.Count; i++)
                        {
                            if (dsparentfunctions.Tables[0].Rows[i][2].ToString() == Constants_Master.Zero)
                            {
                                parentmenu[counter] = new MenuItem();
                                parentmenu[counter].Text = dsparentfunctions.Tables[0].Rows[i][1].ToString();
                                parentmenu[counter].NavigateUrl = dsparentfunctions.Tables[0].Rows[i][6].ToString();
                                parentmenu[counter].Value = dsparentfunctions.Tables[0].Rows[i][0].ToString();
                                Mainmenu.Items.Add(parentmenu[counter]);

                                if (parentmenu[counter].Text != Constants_Master.Logout && parentmenu[counter].Text != "Crop Summary")
                                {
                                    parentmenu[counter].NavigateUrl = "~/agrofpm1/Search/GoogleMapView.aspx";
                                    counter = counter + 1;
                                }
                                else if (parentmenu[counter].Text != "Crop Summary")
                                {
                                    parentmenu[counter].NavigateUrl = "~/agrofpm1/Index.aspx";
                                    counter = counter + 1;
                                }
                                //if (parentmenu[counter].Text != Constants_Master.LoginTimings)
                                //{
                                //    parentmenu[counter].NavigateUrl = "~/agrofpm1/Home.aspx";
                                //    counter = counter + 1;
                                //}
                                //else
                                //{
                                //    parentmenu[counter].NavigateUrl = "~/AgroFPM1/Login.aspx" + "?uname=";
                                //    counter = counter + 1;
                                //}
                            }
                            else
                            {
                                break;
                            }
                        }
                        addchilditems(dsparentfunctions, counter, parentcount, parentmenu);
                        // renameMenuItems(parentmenu, childmenus);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // Response.Write(ex.Message);
        }
    }

    #endregion
    #region addchilditems
    protected void addchilditems(DataSet dsparentfunctions, int counter, int parentcount, MenuItem[] parentmenu)
    {
        try
        {
            //ADDING CHILDITEMS TO MAINMENU ITEMS
            if (Session[Constants_Master.dsfunctions] == null)
            {
                for (int i = 0; i < parentcount; i++)
                {
                    if (parentmenu[i] != null)
                    {

                        dsfunctions = da.fill_menu(Convert.ToString(Session["U_ID"]), parentmenu[i].Value);
                        Session[Constants_Master.dsfunctions] = dsfunctions;
                        function_count = dsfunctions.Tables[0].Rows.Count;
                        checkingchilditems(dsfunctions, parentmenu, i);
                    }
                }
                renameMenuItems(parentmenu, childmenus);

            }
            else
            {
                for (int i = 0; i < parentcount; i++)
                {
                    if (parentmenu[i] != null)
                    {
                        ViewState[Constants_Master.uid] = 1;
                        dsfunctions = da.fill_menu(Convert.ToString(Session["U_ID"]), parentmenu[i].Value);
                        function_count = dsfunctions.Tables[0].Rows.Count;
                        checkingchilditems(dsfunctions, parentmenu, i);
                    }

                }
                renameMenuItems(parentmenu, childmenus);

            }

        }
        catch (Exception ex)
        {
            // Response.Write(ex.Message);
        }
    }

    private void renameMenuItems(MenuItem[] parentmenu, MenuItem[] childmenus)
    {

        for (int ij = 0; ij < parentmenu.Length; ij++)
        {
            if (parentmenu[ij] != null)
            {
                if (parentmenu[ij].Text.Contains("Home"))
                    parentmenu[ij].Text = LangConstants.Home;

                else if (parentmenu[ij].Text.Contains("Logout"))
                    parentmenu[ij].Text = LangConstants.Logout;

                else if (parentmenu[ij].Text.Contains("Seed Crop Management"))
                    parentmenu[ij].Text = LangConstants.SeedCropManagement;

                else if (parentmenu[ij].Text.Contains("Growers"))
                    parentmenu[ij].Text = LangConstants.Growers;

                else if (parentmenu[ij].Text.Contains("Picture Records"))
                    parentmenu[ij].Text = LangConstants.PictureRecords;
            }
        }

    }
    #endregion

    # region checkingchilditems

    protected void checkingchilditems(DataSet dsfunctions, MenuItem[] parentmenu, int i)
    {
        try
        {
            childmenus = new MenuItem[function_count];
            for (int j = 0; j < dsfunctions.Tables[0].Rows.Count; j++)
            {
                childmenus[j] = new MenuItem();
                childmenus[j].Text = dsfunctions.Tables[0].Rows[j][1].ToString();

                string naviurl = dsfunctions.Tables[0].Rows[j][6].ToString();
                childmenus[j].NavigateUrl = naviurl;
                parentmenu[i].ChildItems.Add(childmenus[j]);
                //childmenus[j].Target = "mainframe";

                //dsfunctions = da.fill_menu(Convert.ToString(ViewState["uid"]), dsfunctions.Tables[0].Rows[j][0].ToString());
                //function_count = dsfunctions.Tables[0].Rows.Count;
                //checkingchilditems(dsfunctions, parentmenu, i);

            }

            for (int j = 0; j < childmenus.Length; j++)
            {
                if (childmenus[j].Text.Contains("Grower Details"))
                    childmenus[j].Text = LangConstants.GrowerDetails;

                else if (childmenus[j].Text.Contains("Sowing"))
                    childmenus[j].Text = LangConstants.SowingDetails;

                else if (childmenus[j].Text.Contains("Field"))
                    childmenus[j].Text = LangConstants.FieldInspectionDetails;

                else if (childmenus[j].Text.Contains("Harvest"))
                    childmenus[j].Text = LangConstants.HarvestingDetails;

                else if (childmenus[j].Text.Contains("Report"))
                    childmenus[j].Text = LangConstants.ReportingDetails;
            }
            // addchilditems(dsfunctions,0, dsfunctions.Tables[0].Rows.Count, parentmenu);
        }
        catch (Exception ex)
        {
            // Response.Write(ex.Message);
        }
    }

    #endregion

}